#coding=utf-8
import wx

data = [ 
        ['1',[['1.1', ['1.1.1', '1.1.2']],'1.2']], 
        '2', 
        ['3', ['3.1', '3.2']],
       ]

class TreeFrame(wx.Frame):
    def __init__(self):
        wx.Frame.__init__(self, parent=None, size=(400,300))

        # Create the tree
        pnl = wx.Panel(self)
        self.tree = wx.TreeCtrl(parent=pnl, size=(350, 280))

        # Add a root node
        root = self.tree.AddRoot("test")

        # Add nodes from our data set
        self.AddTreeNodes(root, data)

        # Bind some interesting events
        self.Bind(wx.EVT_TREE_ITEM_EXPANDED, self.OnItemExpanded, self.tree)
        self.Bind(wx.EVT_TREE_ITEM_COLLAPSED, self.OnItemCollapsed, self.tree)
        self.Bind(wx.EVT_TREE_SEL_CHANGED, self.OnSelChanged, self.tree)
        self.Bind(wx.EVT_TREE_ITEM_ACTIVATED, self.OnActivated, self.tree)

        # Expand the first level
        self.tree.Expand(root)


    def AddTreeNodes(self, parentItem, items):
        """
        Recursively traverses the data structure, adding tree nodes to
        match it.
        """
        for item in items:
            if type(item) == str:
                self.tree.AppendItem(parentItem, item)
            else:
                newItem = self.tree.AppendItem(parentItem, item[0])
                self.AddTreeNodes(newItem, item[1])
    
    def FindItem(self, parentItem, text):
        item, cookie = self.tree.GetFirstChild(parentItem)
        
        t = self.GetItemText(item)
        print t
        if t == text:
            return item
        else:
            r = self.FindItem(item, text)
            if r:
                return r
                    
        while item:

            item, cookie = self.tree.GetNextChild(parentItem, cookie)
            t = self.GetItemText(item)
            print t
            if t == text:
                return item
            else:
                r = self.FindItem(item, text)
                if r:
                    return r
        return None
            
    def GetItemText(self, item):
        if item:
            return self.tree.GetItemText(item)
        else:
            return ""

    def OnItemExpanded(self, evt):
        print "OnItemExpanded: ", self.GetItemText(evt.GetItem())

    def OnItemCollapsed(self, evt):
        print "OnItemCollapsed:", self.GetItemText(evt.GetItem())

    def OnSelChanged(self, evt):
        print "OnSelChanged:   ", self.GetItemText(evt.GetItem())

    def OnActivated(self, evt):
        print "OnActivated:    ", self.GetItemText(evt.GetItem())

    def SelectItemByText(self, text):
        item = self.FindItem(self.tree.GetRootItem(), text)
        print item
        if item:
            self.tree.SelectItem(item)
            
app = wx.PySimpleApp()
frame = TreeFrame()
frame.SelectItemByText('1.1.2')
frame.Show()
app.MainLoop()

